﻿#include "tetrisboard.h"

TetrisBoard::TetrisBoard(QWidget *parent)
    : QFrame(parent), isStarted(false), isPausedState(false), isGameOverState(false)
{
    setFrameStyle(QFrame::Panel | QFrame::Sunken);
    setFocusPolicy(Qt::StrongFocus);
    clearBoard();

    nextPiece.setRandomShape();
    connect(&timer, &QTimer::timeout, this, &TetrisBoard::oneLineDown);
}

void TetrisBoard::start()
{
    if (isPausedState)
        return;

    isStarted = true;
    isGameOverState = false;
    isPausedState = false;
    numLinesRemoved = 0;
    numPiecesDropped = 0;
    score = 0;
    level = 1;
    clearBoard();

    emit scoreChanged(score);
    emit levelChanged(level);
    emit linesRemovedChanged(numLinesRemoved);

    newPiece();
    timer.setInterval(timeoutTime());
    timer.start();
}

void TetrisBoard::pause()
{
    if (!isStarted)
        return;

    isPausedState = !isPausedState;
    if (isPausedState) {
        timer.stop();
    } else {
        timer.start();
    }
    update();
}

int TetrisBoard::timeoutTime() const
{
    return 1000 - (level - 1) * 80;
}

void TetrisBoard::clearBoard()
{
    for (int i = 0; i < BoardHeight; ++i)
        for (int j = 0;j < BoardWidth; ++j)
            board[i][j] = TetrisPiece::NoShape;
}

void TetrisBoard::paintEvent(QPaintEvent *event)
{
    QFrame::paintEvent(event);

    QPainter painter(this);
    QRect rect = contentsRect();

    if (isPausedState) {
        painter.setPen(Qt::white);
        painter.setFont(QFont("Arial", 24, QFont::Bold));
        painter.drawText(rect, Qt::AlignCenter, u8"游戏暂停");
        return;
    }

    if (isGameOverState) {
        painter.setPen(Qt::red);
        painter.setFont(QFont("Arial", 24, QFont::Bold));
        painter.drawText(rect, Qt::AlignCenter, u8"游戏结束");
        return;
    }

    int boardTop = rect.bottom() - BoardHeight * squareHeight();

    // 绘制游戏板上的方块
    for (int i = 0; i < BoardHeight; ++i) {
        for (int j = 0; j < BoardWidth; ++j) {
            TetrisPiece::PieceShape shape = shapeAt(j, BoardHeight - i - 1);
            if (shape != TetrisPiece::NoShape)
                drawSquare(painter, rect.left() + j * squareWidth(),
                           boardTop + i * squareHeight(), shape);
        }
    }

    // 绘制当前方块
    if (curPiece.shape() != TetrisPiece::NoShape) {
        for (int i = 0; i < 4; ++i) {
            int x = curX + curPiece.x(i);
            int y = curY - curPiece.y(i);
            drawSquare(painter, rect.left() + x * squareWidth(),
                       boardTop + (BoardHeight - y - 1) * squareHeight(),
                       curPiece.shape());
        }
    }
}

void TetrisBoard::drawSquare(QPainter &painter, int x, int y, TetrisPiece::PieceShape shape)
{
    static const QColor colors[] = {
        QColor(0, 0, 0),
        QColor(231, 76, 60),    // 红色 - Z
        QColor(46, 204, 113),   // 绿色 - S
        QColor(52, 152, 219),   // 蓝色 - I
        QColor(155, 89, 182),   // 紫色 - T
        QColor(241, 196, 15),   // 黄色 - O
        QColor(230, 126, 34),   // 橙色 - L
        QColor(41, 128, 185)    // 深蓝 - J
    };

    QColor color = colors[shape];
    painter.fillRect(x + 1, y + 1, squareWidth() - 2, squareHeight() - 2, color);

    painter.setPen(color.lighter());
    painter.drawLine(x, y + squareHeight() - 1, x, y);
    painter.drawLine(x, y, x + squareWidth() - 1, y);

    painter.setPen(color.darker());
    painter.drawLine(x + 1, y + squareHeight() - 1,
                     x + squareWidth() - 1, y + squareHeight() - 1);
    painter.drawLine(x + squareWidth() - 1, y + squareHeight() - 1,
                     x + squareWidth() - 1, y + 1);
}

void TetrisBoard::keyPressEvent(QKeyEvent *event)
{
    if (!isStarted || isGameOverState || curPiece.shape() == TetrisPiece::NoShape) {
        QFrame::keyPressEvent(event);
        return;
    }

    switch (event->key()) {
    case Qt::Key_Left:
        moveLeft();
        break;
    case Qt::Key_Right:
        moveRight();
        break;
    case Qt::Key_Down:
        oneLineDown();
        break;
    case Qt::Key_Up:
        rotateLeft();
        break;
    case Qt::Key_Space:
        dropDown();
        break;
    case Qt::Key_P:
        pause();
        break;
    default:
        QFrame::keyPressEvent(event);
    }
}

void TetrisBoard::timerEvent(QTimerEvent *event)
{
    if (event->timerId() == timer.timerId()) {
        if (isPausedState)
            return;
        oneLineDown();
    } else {
        QFrame::timerEvent(event);
    }
}

void TetrisBoard::newPiece()
{
    curPiece = nextPiece;
    nextPiece.setRandomShape();
    emit nextPieceChanged();

    curX = BoardWidth / 2 - 1;
    curY = BoardHeight - 1 + curPiece.minY();

    if (!tryMove(curPiece, curX, curY)) {
        curPiece.setShape(TetrisPiece::NoShape);
        timer.stop();
        isStarted = false;
        isGameOverState = true;
        emit gameOver();
    }
}

bool TetrisBoard::tryMove(const TetrisPiece &newPiece, int newX, int newY)
{
    for (int i = 0; i < 4; ++i) {
        int x = newX + newPiece.x(i);
        int y = newY - newPiece.y(i);
        if (x < 0 || x >= BoardWidth || y < 0 || y >= BoardHeight)
            return false;
        if (shapeAt(x, y) != TetrisPiece::NoShape)
            return false;
    }

    curPiece = newPiece;
    curX = newX;
    curY = newY;
    update();
    return true;
}

void TetrisBoard::removeFullLines()
{
    int numFullLines = 0;

    for (int i = BoardHeight - 1; i >= 0; --i) {
        bool lineIsFull = true;

        for (int j = 0; j < BoardWidth; ++j) {
            if (shapeAt(j, i) == TetrisPiece::NoShape) {
                lineIsFull = false;
                break;
            }
        }

        if (lineIsFull) {
            ++numFullLines;
            for (int k = i; k < BoardHeight - 1; ++k) {
                for (int j = 0; j < BoardWidth; ++j)
                    setShapeAt(j, k, shapeAt(j, k + 1));
            }
            for (int j = 0; j < BoardWidth; ++j)
                setShapeAt(j, BoardHeight - 1, TetrisPiece::NoShape);
        }
    }

    if (numFullLines > 0) {
        numLinesRemoved += numFullLines;
        score += numFullLines * numFullLines * 100 * level;
        level = numLinesRemoved / 10 + 1;

        emit scoreChanged(score);
        emit levelChanged(level);
        emit linesRemovedChanged(numLinesRemoved);

        timer.start();
        update();
    }
}

TetrisPiece::PieceShape TetrisBoard::shapeAt(int x, int y) const
{
    return board[y][x];
}

void TetrisBoard::setShapeAt(int x, int y, TetrisPiece::PieceShape shape)
{
    board[y][x] = shape;
}

void TetrisBoard::dropDown()
{
    int dropHeight = 0;
    int newY = curY;

    while (newY > 0) {
        if (!tryMove(curPiece, curX, newY - 1))
            break;
        --newY;
        ++dropHeight;
    }

    pieceDropped();
    score += dropHeight;
    emit scoreChanged(score);
}

void TetrisBoard::oneLineDown()
{
    if (!tryMove(curPiece, curX, curY - 1))
        pieceDropped();
}

void TetrisBoard::pieceMoved()
{
    update();
}

void TetrisBoard::pieceDropped()
{
    for (int i = 0; i < 4; ++i) {
        int x = curX + curPiece.x(i);
        int y = curY - curPiece.y(i);
        setShapeAt(x, y, curPiece.shape());
    }

    removeFullLines();
    if (!isGameOverState)
        newPiece();
}

void TetrisBoard::rotateLeft()
{
    if (tryMove(curPiece.rotatedLeft(), curX, curY))
        update();
}

void TetrisBoard::rotateRight()
{
    if (tryMove(curPiece.rotatedRight(), curX, curY))
        update();
}

void TetrisBoard::moveLeft()
{
    if (tryMove(curPiece, curX - 1, curY))
        update();
}

void TetrisBoard::moveRight()
{
    if (tryMove(curPiece, curX + 1, curY))
        update();
}
